package com.xiaoxu.springboot.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class MyAop {
    private final static Logger LOGGER= LoggerFactory.getLogger(MyAop.class);
    @Pointcut("execution(public * com.xiaoxu.springboot.modules.*.controller.*(..))")
    @Order(1)
    public void controllerPointCut(){};

    @Pointcut("@annotation(com.xiaoxu.springboot.aop.MyAnnotation)")
    public void annotationPointCut(){};

    @Before(value = "controllerPointCut()")
    public void beforeControllerAop(JoinPoint joinPoint){
        LOGGER.debug("===before===");
        ServletRequestAttributes attr=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attr.getRequest();
        LOGGER.debug(String.format("请求来源： %s",request.getRemoteAddr()));
        LOGGER.debug(String.format("请求URL： %s",request.getRequestURL()));
        LOGGER.debug(String.format("请求方式： %s",request.getMethod()));

    }

    @Around(value = "controllerPointCut()")
    public Object aroundController(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
    }

    @After(value = "controllerPointCut()")
    public void afterController() {
        LOGGER.debug("===after===");
    }

    @Around(value = "annotationPointCut()")
    public Object arountAnnotationAop(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        long start=System.currentTimeMillis();
        Object object=proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
        long end=System.currentTimeMillis();
        LOGGER.debug(String.format("方法执行时间： %s", (end -  start)));
        return object;
    }
}
